<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ include file="/views/common/taglibs.jsp" %>
<!DOCTYPE>
<html>
  <head>
	  <!-- 引入通用js、css文件(xiaogq) -->
	  <meta name="decorator" content="default">
	  <link rel="stylesheet" type="text/css" href="${ctx}/css/common/operation/sys_operation.css"/>
	  <link rel="stylesheet" type="text/css" href="${ctx}/css/common/export/import_field_match.css"/>
  </head>
  
  <body>
	  <div class="button_list">
		  <a href="javascript:;" onclick="lastStep(this);">
			<span class="span_button">
				<span><img src="${ctx}/image/common/operation/oper_preStep.png"></span>
				<span name="buTitle">上一步</span>
			</span>
		  </a>
		  <a href="javascript:;" onclick="nextStep(this);">
			<span class="span_button">
				<span><img src="${ctx}/image/common/operation/oper_nextStep.png"></span>
				<span name="buTitle">下一步</span>
			</span>
		  </a>
		  <a href="javascript:;" onclick="javascript:parent.closeTab();">
			<span class="span_button">
				<span><img src="${ctx}/image/common/operation/oper_CANCEL.png"></span>
				<span name="buTitle">取消</span>
			</span>
		  </a>
	  </div>

	  <div class="content-wrap">
	      <div class="import-warning" style="width:98%;">
			  <p class="import-txt">1.在Excel文件字段中，选择与CRM系统匹配的字段列，且选择的字段列不能重复 </p>
			  <p class="import-txt">2.对引用字段，选择可以在系统中按名称查找对应记录的字段</p>
		  </div>
		  <div class="import-w">
		  <div class="import-header">系统属性</div>
          <table class="table-report" style="width:80%;margin:5px 5px 5px;border-left: 1px solid #BBBBBB;border-right: 0 none;">
              <tr>
				  <th>CRM属性</th>
				  <th>导入属性</th>
				  <th>CRM属性</th>
				  <th>导入属性</th>
              </tr>
          <tr>
          <c:forEach var="m" items="${mainFields}" varStatus="temp">
          	<c:if test="${temp.index%2==0}">
				<c:choose>
					<c:when test="${temp.index%4==0}">
						<tr style="background:#f0f0f0;">
					</c:when>
					<c:otherwise>
						<tr>
					</c:otherwise>
				</c:choose>
          	</c:if>
             <td style="border-right: 1px solid #BBBBBB;border-left: 0 none;"><div dbname="${m.name}" fieldid="${m.id}">${m.inchinese}</div></td>
              <td style="border-right: 1px solid #BBBBBB;border-left: 0 none;">
              		<div class="select-div">
		                <select name="mainFieldMatch" class="tb-select select-val" nulldisable="${m.nulldisable}" valueunique="${m.valueUnique}" inchinese="${m.inchinese}" style="border:none;">
		                   <c:set var="boo" scope="session" value="true"></c:set>
		                   <c:forEach var="l" items="${list}" varStatus="stat">
		                     <c:choose>
		                        <c:when test="${m.inchinese == l }">
		                           <option value="${stat.count}" selected="selected">${stat.count}：${l}</option>
		                           <c:set var="boo" scope="session" value="false"></c:set>
		                        </c:when>
		                        <c:otherwise>
		                           <option value="${stat.count}">${stat.count}：${l }</option>
		                        </c:otherwise>
		                     </c:choose>
		                   </c:forEach>
		                   <c:choose>
		                     <c:when test="${sessionScope.boo == 'true'}">
		                        <option value="空" selected="selected">空</option>
		                     </c:when>
		                     <c:otherwise>
		                        <option value="空">空</option>
		                     </c:otherwise>
		                   </c:choose>
		                </select>
		            </div>
              </td>
          </c:forEach>
            </tr>
        </table>
      </div>
      
      <div class="import-w" style="margin-bottom:10px;">
      	<div class="import-header">引用属性</div>
        <table class="table-report" style="width:80%;margin:5px 5px 5px;">
        	<tr>
          <c:forEach var="p" items="${map}" varStatus="temp1">
             <c:if test="${temp1.index%2==0}">
          		<tr>
          	 </c:if>
               <td>
                  <select name="danymicQuoteField" class="tb-select">
                    <c:forEach var="pl" items="${p.value }">
                        <c:choose>
                           <c:when test="${pl.name == 'name'}">
                              <option selected="selected" qdbname="${p.key.name }" dbname="${pl.name }" qdfieldid="${pl.id}">${p.key.inchinese }：${pl.inchinese }</option>
                           </c:when>
                           <c:otherwise>
                              <option qdbname="${p.key.name }" dbname="${pl.name }" qdfieldid="${pl.id}">${p.key.inchinese }：${pl.inchinese }</option>
                           </c:otherwise>
                        </c:choose>
                    </c:forEach>
                  </select>
               </td>
               <td class="quoteclass">
                  <div class="select-div">
	                  <select name="quoteFieldMatch" class="tb-select select-val" nulldisable="${p.key.nulldisable}" valueunique="${p.key.valueUnique}" inchinese="${p.key.inchinese }" style="border:none;">
	                    <c:set var="boo" scope="session" value="true"></c:set>
	                    <c:forEach var="l" items="${list}" varStatus="stat">
		                    <c:choose>
		                      <c:when test="${p.key.inchinese == l }">
		                         <option value="${stat.count }" selected="selected">${stat.count }:${l }</option>
		                         <c:set var="boo" scope="session" value="false"></c:set>
		                      </c:when>
		                      <c:otherwise>
		                         <option value="${stat.count }">${stat.count }:${l }</option>
		                      </c:otherwise>
		                    </c:choose>
		                 </c:forEach>
		                 <c:choose>
		                     <c:when test="${sessionScope.boo == 'false'}">
		                        <option>空</option>
		                     </c:when>
		                     <c:otherwise>
		                        <option selected="selected">空</option>
		                     </c:otherwise>
			             </c:choose>
	                  </select>
                  </div>
               </td>
          </c:forEach>
            </tr>
        </table>
      </div>
    </div>
	  <!-- 通用导出成功提示下载模态框 -->
	  <div class="modal fade" id="exportModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>

	  <script type="text/javascript" src="${ctx}/js/widget/bootstrap/bootstrap.min.js"></script>
	  <script type="text/javascript" src="${ctx}/js/common/export/entity_export.js"></script>
	  <script type="text/javascript">
		  $(document).ready(function(){
			  //为所有的checkbox赋值
			  $("input[type='checkbox']").click(function(){
				  if(this.checked){
					  $(this).attr("value","true");
				  }else{
					  $(this).attr("value","false");
				  }
			  });
			  $(".select-val").each(function(index,domEle){
				  //得到必填项
				  var nulldisable = $(domEle).attr("nulldisable");
				  //如果是必填字段
				  if(nulldisable == 'true'){
					  if($(domEle).val() == '空'){
						  //标记红色
						  $(this).parent().css("border-left","3px solid #FF0000");
					  }
				  }
			  });
			  //值改变事件
			  $(".select-val").change(function(){
				  //得到必填项
				  var nulldisable = $(this).attr("nulldisable");
				  //如果是必填字段
				  if(nulldisable == 'true'){
					  if($(this).val() == '空'){
						  $(this).parent().css("border-left","3px solid #FF0000");
					  }else{
						  $(this).parent().css("border-left","1px solid #BBB");
					  }
				  }
			  });
		  });

		  //上一步
		  function lastStep(){
			  var entityId = "${entityId}";
			  var entityName = "${entityName}";
			  var fileName =  "${fileName}";
			  var lastFieldName = fileName.substring(fileName.lastIndexOf("."));
			  var url="";
			  if(lastFieldName == ".csv"){
				  url="ExportImport/importchoosefile.do?entityId="+entityId+"&entityName="+entityName;
				  parent.replaceIframe({title:"导入:"+entityName,url:url});
			  }else{
				  url="ExportImport/showImportFileTable.do?entityId="+entityId+"&entityName="+entityName+"&fileName="+fileName;
				  parent.replaceIframe({title:"导入:"+entityName+":选择工作表",url:url});
			  }
		  }

		  //导入通用方法
		  function nextStep(){
			  var error = true,eoorr2 = false,errortext = "";
			  var fieldValue = new Array();
			  //导入数据是先验证必填字段不能为空
			  $(".select-val").each(function(index,domEle){
				  //得到必填项
				  var nulldisable = $(domEle).attr("nulldisable");
				  //如果是必填字段
				  if(nulldisable == 'true'){
					  var inchinese = $(domEle).attr("inchinese");
					  if($(domEle).val() == '空'){
						  error = false;
					  }
				  }
				  if($(domEle).val() != '空'){
					  fieldValue.push($(domEle).find("option:selected").text());
				  }
			  });
			  if(!error){
				  alert("必填项字段不能为空请选择必填项!");
				  return false;
			  }

			  var newFieldValue = fieldValue.sort();
			  for(var i = 0; i < fieldValue.length; i++){
				  if(newFieldValue[i] == newFieldValue[i+1]){
					  errortext = newFieldValue[i];
					  eoorr2 = true;
				  }
			  }
			  if(eoorr2){
				  alert("匹配Excel文件中第"+errortext+"列重复,请重新匹配!");
				  return false;
			  }
			  var entityId = "${entityId}";
			  var fileName = "${fileName}";
			  //获取后台需要导入的参数
			  var json="";
			  $("select[name='mainFieldMatch']").each(function(index,domEle){//非引用字段
				  var selectValue = $(domEle).val();
				  if(selectValue != '空'){
					  var divEle = $(domEle).parent("div").parent('td').prev().children("div");
					  var checkEle = $(domEle).parent("div").parent('td').next().children("input[name='checkboxs']");
					  var fieldName = $(divEle).attr("dbname");
					  var lastName = fieldName.substring(fieldName.lastIndexOf("_"));
					  if(lastName != "_mutibox"){
						  json = json+",{";
						  json = json+'"index":"'+$(domEle).val()+'",'; //导入字段匹配顺序
						  json = json+'"fieldName":"'+fieldName+'",'; //字段名称
						  json = json+'"fieldid":"'+$(divEle).attr("fieldid")+'",';  //对应字段表中id
						  json = json+'"required":"'+$(domEle).attr("nulldisable")+'",';//是否是必填字段
						  json = json+'"vunique":"'+$(domEle).attr("valueunique")+'",';//是否取值为一
						  json = json+'"inchinese":"'+$(domEle).attr("inchinese")+'",';//字段中文名称
						  json = json+'"primaryField":"'+$(checkEle).val()+'"}';  //字段是否作为主键(即可作为数据过滤条件，也可以作为数据查重条件)
					  }
				  }
			  });
			  $("select[name='quoteFieldMatch']").each(function(index,domEle){//实体引用字段
				  var selectValue = $(domEle).val();
				  if(selectValue != '空'){
					  var selEle = $(domEle).parent("div").parent('td').prev().children('select[name="danymicQuoteField"]').children('option:selected');
					  var checkEle = $(domEle).parent("div").parent('td').next().children("input[name='checkboxs']");
					  var fieldName = $(selEle).attr("qdbname");
					  var lastName = fieldName.substring(fieldName.lastIndexOf("_"));
					  if(lastName != "_mutibox"){
						  json = json+",{";
						  json = json+'"index":"'+$(domEle).val()+'",'; //导入字段的匹配顺序
						  json = json+'"fieldName":"'+fieldName+'",'; //引用字段名
						  json = json+'"fieldid":"'+$(selEle).attr("qdfieldid")+'",'; //引用字段对应在字段表中的id
						  json = json+'"required":"'+$(domEle).attr("nulldisable")+'",';//是否是必填字段
						  json = json+'"vunique":"'+$(domEle).attr("valueunique")+'",';//是否取值为一
						  json = json+'"inchinese":"'+$(domEle).attr("inchinese")+'",';//字段中文名称
						  json = json+'"primaryField":"'+$(checkEle).val()+'"}'; //字段是否作为主键(即可作为数据过滤条件，也可以作为数据查重条件)
					  }
				  }
			  });
			  //console.log("json====",json);
			  //执行导入
			  if(json != ""){
				  $.ajax({
					  type: "post",
					  url: "${ctx}/ExportImport/importEntity.do",
					  data: {entityId:entityId,importFieldJsonChar:"["+json.substring(1)+"]"},
					  dataType: "json",
					  success: function(data) {
						  if(data.importSuc){
							  if(data.boo){//如果导入数据成功
								  var text = "成功导入"+data.successNumber+"条数据，失败导入数据"+(data.allNumber-data.successNumber)+"条，导入数据中的数据格式错误"+eval(data.allNumber-data.successNumber)+"条<br>"
								  if(data.bool){//存在错误数据
									  text += "请点击下载：<a href='${ctx}/views/common/export/export_file_download.jsp?path="+data.path+"&name="+data.name+"' style='color:blue' >需要下载的excel</a> "
									  exportAlert("导入提示",text);
								  }else{
									  text += "无错误数据";
									  exportAlert("导入提示",text);
								  }
							  }else{//导入数据时发生错误
								  alert("导出错误数据时发生异常!");
							  }
						  }else{
							  alert("导入数据失败,文件字段与系统字段类型不对应!");
						  }
					  }
				  });
			  }else{
				  alert("请选择需要导入的实体属性!");
			  }
		  }
	  </script>
  </body>
</html>